package com.code.wifi.activity;

import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.code.wifi.Apater.WifiListAdapter;
import com.code.wifi.R;
import com.code.wifi.broadcast.WifiReceiver;
import com.code.wifi.control.WifiControl;
import com.code.wifi.listener.OnWifiConnectListener;
import com.code.wifi.listener.WifiReceiverActionListener;

import java.util.List;

/**
 * Wifi 主界面
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private final static String TAG = MainActivity.class.getSimpleName();
    private WifiControl wifiControl;//wifi控制器
    private ListView wifiListView;//列表
    private ToggleButton btOpenOrClose;//开/关 wifi
    private ImageView ivScanWifi;//扫描wifi
    private ProgressBar circleProgress;//进度条
    private WifiReceiver wifiReceiver;//wifi 广播
    private TextView tvWifiHint;//wifi 的提示
    private WifiReceiverActionListener listener;//Wifi 广播回调接口 更新UI
    private OnWifiConnectListener connectListener;//wifi 连接监听回调接口
    private List<ScanResult> wifiScanResult; //Wifi 列表

    /*
       是否可以获取 wifi 的扫描结果
       该值防止 onWifiScanResultBack 方法频繁更新UI（ListView）
       从 logcat 输出可以看出，开启wifi后，系统一直会发送
       SCAN_RESULTS_AVAILABLE_ACTION 的广播
     */
    private boolean isOk2GetResult;
    private WifiListAdapter mAdapter;//Wifi 列表适配器
//    private View viewOfWifiConnected;//连接的 wifi 所在的 View


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取 Wifi 控制器单利实例
        wifiControl = WifiControl.getInstance(MainActivity.this);
        WifiInfo wifiInfo = wifiControl.getConnectionInfo();
        if (null != wifiInfo) {
            boolean isDisconnect = wifiControl.disconnectWifi(wifiInfo.getNetworkId());
        }
        initView();
        initListener();
        initData();
    }

    /**
     * 初始化界面
     */
    public void initView() {
        wifiListView = (ListView) findViewById(R.id.wifi_list);
        btOpenOrClose = (ToggleButton) findViewById(R.id.bt_open_or_close);
        ivScanWifi = (ImageView) findViewById(R.id.iv_scan_wifi);
        tvWifiHint = (TextView) findViewById(R.id.tv_wifi_hint);
        circleProgress = (ProgressBar) findViewById(R.id.circle_progress);
        //根据wifi的状态设置Button
        btOpenOrClose.setChecked(wifiControl.isWifiEnable());
        //判断wifi可用状态，设置提示信息
        if (wifiControl.isWifiEnable()) {
            tvWifiHint.setText("");
            tvWifiHint.setHeight(0);
        }
    }

    /**
     * 初始化监听器
     */
    public void initListener() {
        wifiListView.setOnItemClickListener(this);
        btOpenOrClose.setOnClickListener(this);
        ivScanWifi.setOnClickListener(this);

        /*
          这个接口实现是用于得到wifi广播的通知
         */
        listener = new WifiReceiverActionListener() {

            @Override
            public void onWifiOpening() {
                Log.i(TAG, "onWifiOpening...");
                //设置提示信息
                tvWifiHint.setText(R.string.wifi_connection_hint);
                //设置高度
                tvWifiHint.setHeight(40);
                //设置按钮的状态
                btOpenOrClose.setEnabled(false);
            }

            @Override
            public void onWifiOpened() {
                Log.i(TAG, "onWifiOpened...");
//                //设置Button为开
//                btOpenOrClose.setChecked(true);
                //允许获取扫描结果值
                isOk2GetResult = true;
                //清除连接提示
                tvWifiHint.setText("");
                //设置高度
                tvWifiHint.setHeight(0);
                //去扫描WIFI
//                wifiControl.launchScan();
                //显示圆形进度条
                circleProgress.setVisibility(View.VISIBLE);
            }


            @Override
            public void onWifiClosed() {
                Log.i(TAG, "onWifiClosed...");
                //设置Button
                btOpenOrClose.setChecked(false);
                //设置提示信息
                tvWifiHint.setText(R.string.wifi_disconnection_hint);
                //设置高度
                tvWifiHint.setHeight(40);
            }

            @Override
            public void onWifiClosing() {
                Log.i(TAG, "onWifiClosing...");
                //清空wifi列表
                wifiScanResult = null;
                //重新设置 Wifi List 的内容
                mAdapter.setMWifiList(wifiScanResult);
                //更新 ListView
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onWifiScanResultBack() {
                Log.i(TAG, "onWifiScanResultBack...");
                //设置Button为开
                btOpenOrClose.setEnabled(true);
                if (isOk2GetResult) {
                    //在这里获取wifi的扫描结果
                    wifiScanResult = wifiControl.getWifiScanResult();
                    //扫描到结果以后,就开始更新界面
                    if (null != wifiScanResult) {
                        Log.i(TAG, "size == " + wifiScanResult.size());
                        if (mAdapter != null) {
                            //重新设置 Wifi List 的内容
                            mAdapter.setMWifiList(wifiScanResult);
                            //更新 ListView
                            mAdapter.notifyDataSetChanged();
                        }

                    } else {
                        Log.i(TAG, "scan result ==  null");
                    }
                    //禁止获取 wifiScanResult
                    isOk2GetResult = false;

                }
                //隐藏进度条
                circleProgress.setVisibility(View.GONE);


            }

            @Override
            public void onWifiConnected(WifiInfo wifiInfo) {
                Log.i(TAG, "onWifiConnected...");
                //获得当前连接的 wifi 的连接状态提示框
                TextView wifiStatus = (TextView) MainActivity.this.locateCrtView().findViewById(R.id.wifi_status);
                //设置高度
                wifiStatus.setHeight(35);
                //设置内容
                wifiStatus.setText(R.string.wifi_connected);
                //设置颜色
                wifiStatus.setTextColor(MainActivity.this.getResources().getColor(R.color.colorPrimaryDark));

//                LinearLayout wifiContent = (LinearLayout) MainActivity.this.locateCrtView().findViewById(R.id.wifi_content);
//                TextView textView = new TextView(MainActivity.this);
//                textView.setText("已连接");
//                //设置TextView 布局
//                textView.setLayoutParams(
//                        new ViewGroup.LayoutParams(
//                                ViewGroup.LayoutParams.MATCH_PARENT,
//                                ViewGroup.LayoutParams.WRAP_CONTENT
//                        ));
//                wifiContent.addView(textView);
            }
        };

        /*
         * 用于处理wifi连接
         */
        connectListener = new OnWifiConnectListener() {
            @Override
            public void onStart(ScanResult scanResult) {
                Log.i(TAG, "----onStart" + scanResult.SSID);
                if (MainActivity.this.locateCrtView() != null) {
                    //获得当前连接的 wifi 的连接状态提示框
                    TextView wifiStatus = (TextView) MainActivity.this.locateCrtView().findViewById(R.id.wifi_status);
                    //设置高度
                    wifiStatus.setHeight(0);
                    //设置内容
                    wifiStatus.setText("");
                }
            }

            @Override
            public void onFailure(ScanResult scanResult) {
                Log.i(TAG, "----onFailure" + scanResult.SSID);
                dialog(scanResult);
            }

            @Override
            public void onFinished() {
                Log.i(TAG, "----onFinished");
            }
        };
    }

    /**
     * 初始化数据对象
     */
    public void initData() {
        //实例化wifi列表
        mAdapter = new WifiListAdapter(wifiScanResult, MainActivity.this);
        //注册广播
        registerBroadcastReceiver();
        //为LstView设置适配器
        wifiListView.setAdapter(mAdapter);
    }


    /**
     * 注册广播，添加过滤器
     */
    public void registerBroadcastReceiver() {

        //实例化过滤器
        IntentFilter filter = new IntentFilter();

        //设置意图过滤
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

        if (null != listener) {
            //实例化广播
            wifiReceiver = new WifiReceiver(listener);
            //注册广播
            registerReceiver(wifiReceiver, filter);
            Log.i(TAG, "------listener is not null");
        }

    }


    /**
     * 点击事件监听  事件有开/关wifi、扫描列表
     *
     * @param v view
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //开/关wifi
            case R.id.bt_open_or_close:
                wifiControl.openOrCloseWifi();
                break;
            //扫描 刷新wifi列表
            case R.id.iv_scan_wifi:
                //开启扫描
                wifiControl.launchScan();
                //显示进度条
                circleProgress.setVisibility(View.VISIBLE);
                //允许获取列表
                isOk2GetResult = true;
                break;
        }
    }


    /**
     * Implement the OnItemClickListener interface used to alert a dialog which is used to connect
     * the wifi you has configured
     *
     * @param parent   parent
     * @param view     view
     * @param position position
     * @param id       id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != wifiScanResult) {
            //获取点击的 Wifi
            ScanResult scanResult = wifiScanResult.get(position);
            //获取 Wifi network id
            int networkId = wifiControl.getNetWorkIdFromConfigure(scanResult);
            //连接指定的已配置的 wifi
            if (networkId != -1) {
                wifiControl.connectWifiByNetworkId(scanResult, networkId, connectListener);
                return;
            }
            //wifi 未配置密码时弹框
            dialog(wifiScanResult.get(position));


        }
    }

    /**
     * 显示自定义dialog，输入密码连接
     *
     * @param scanResult 选中的wifi
     */
    protected void dialog(final ScanResult scanResult) {
        TextView tvWifiName;
        final EditText etPwd;
        Button btConnect, btCancel;

        //定义一个对话框Builder
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //获取布局加载器
        LayoutInflater inflater = getLayoutInflater();
        //加载自定义的布局
        View contentView = inflater.inflate(R.layout.dialog_view_connect, (ViewGroup) findViewById(R.id.dialog_connect));
        //实例化dialog对象
        final AlertDialog dialog = builder.setView(contentView).show();

        //初始化话Dialog界面布局对象
        // ====== start =======
        tvWifiName = (TextView) contentView.findViewById(R.id.tv_wifi_name);
        etPwd = (EditText) contentView.findViewById(R.id.et_pwd);
        btConnect = (Button) contentView.findViewById(R.id.bt_connect);
        btCancel = (Button) contentView.findViewById(R.id.bt_cancel);

        tvWifiName.setText(scanResult.SSID);
        // ======== end =======


        btConnect.setOnClickListener(new View.OnClickListener() {
            String pwd;

            @Override
            public void onClick(View v) {
                pwd = etPwd.getText().toString();
                wifiControl.connectWifiByPwd(scanResult, pwd, connectListener);
                dialog.dismiss();
            }
        });

        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话框
//                Toast.makeText(FlagManageActivity.this, "点击了取消按钮", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*
         * 进行取消注册，否则会导致内存泄露
         */
        if (null != wifiReceiver) {
            unregisterReceiver(wifiReceiver);
            wifiReceiver = null;
            listener = null;
        }
        Log.i(TAG, "----onDestroy >>" + listener);
    }

    /**
     * 获取连接 Wifi 所在 View
     *
     * @return The view that wifi connected locates。
     */
    public View locateCrtView() {
        //已连接 wifi 名称
        String wifiConnectedName = wifiControl.getConnectionInfo().getSSID();
        View view = null;
        //存在连接 wifi 且 listView 不为空进行处理
        if (null != wifiScanResult && null != wifiListView) {
            //判断当前连接的 wifi 的 position
            for (int i = 0; i < wifiScanResult.size(); i++) {
                String str = String.format("\"%s\"", wifiScanResult.get(i).SSID);
                if (wifiConnectedName.equals(str)) {
                    Log.i(TAG, "locateCrtView: ——" + wifiConnectedName);
                    view = wifiListView.getChildAt(i);
                    break;
                }
            }
        }
        return view;
    }
}
